//
//  LocationService.m
//  YRSideViewController
//
//  Created by xiabin on 14/12/30.
//  Copyright (c) 2014年 YueRuo. All rights reserved.
//

#import "LocationService.h"
#import "UMNetworkManager.h"
#define LocationServiceId 199

static LocationService *sharedLocationService;



@implementation LocationService

+(LocationService*)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedLocationService=[[LocationService alloc]init];
    });
    return sharedLocationService;
}

- (void)initService
{
    locationManager = [[CLLocationManager alloc] init];
    if ([CLLocationManager locationServicesEnabled]) {
        NSLog( @"Starting CLLocationManager" );
        locationManager.delegate = self;
        locationManager.distanceFilter = 10;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
            [locationManager requestWhenInUseAuthorization];
        }
    } else {
        [MobClick event:@"LocationFailed"];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    [locationManager stopUpdatingLocation];
    _latitude = newLocation.coordinate.latitude;
    _longtitude = newLocation.coordinate.longitude;
    
    NSLog(@"%f %f",_latitude, _longtitude);
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
                    
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error) {
        if (array.count > 0) {
            CLPlacemark *placemark = [array objectAtIndex:0];
            //获取城市
            self.cityName = placemark.locality;
            if (!self.cityName) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                self.cityName = placemark.administrativeArea;
            }
        }
        NSLog(@"%@",self.cityName);
        
        self.cityName = [self.cityName substringWithRange:(NSMakeRange(0,self.cityName.length-1))];
        
        for(id<UMAsyncJobDelegate> dv in requiredDelegateArr) {
            if ([dv respondsToSelector:@selector(UMAsyncJobDone:JobCookie:And:)]) {
                [dv UMAsyncJobDone:TRUE JobCookie:LocationServiceId And:self.cityName];
            }
        }
        [requiredDelegateArr removeAllObjects];
    }];
}

-(int) getCurrentLocation: (id<UMAsyncJobDelegate>)JobDelegate {
    if(requiredDelegateArr == nil) {
        requiredDelegateArr = [NSMutableArray new];
    }
    [requiredDelegateArr addObject:JobDelegate];
    [locationManager startUpdatingLocation];
    return LocationServiceId;
}

@end
